package com.cn.xiongmeng.czlxz.activity;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.anythink.interstitial.api.ATInterstitial;
import com.cn.xiongmeng.czlxz.MainApplication;
import com.cn.xiongmeng.czlxz.R;
import com.cn.xiongmeng.czlxz.taku.InterstitialAd;
import com.cn.xiongmeng.czlxz.taku.RewardVideoAd;
import com.cn.xiongmeng.czlxz.ui.BannerFragment;
import com.cn.xiongmeng.czlxz.ui.DefeatFragment;
import com.cn.xiongmeng.czlxz.ui.VictoryFragment;
import com.cn.xiongmeng.czlxz.ui.WenzhangFragment;
import com.cn.xiongmeng.czlxz.utils.IntervalControler;

import java.util.Random;

public class WorkActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainApplication:WorkActivity";
    private LinearLayout aixins;
    private TextView tvZhanshi;
    public WenzhangFragment wenzhangFragment;
    private VictoryFragment victoryFragment;
    private DefeatFragment defeatFragment;
    private int curLifeValue; // 当前关卡，剩余生命值
    private int totalIncorrectChar; // 当前关卡，所有错字总数
    private int curFindedIncorrectChar; // 当前关卡，已经找出来的错字数
    private int savedLifeValue = 3; // 当前关卡，剩余生命值
    private int savedFindedIncorrectChar = 0; // 当前关卡，已经找出来的错字数
    private FrameLayout bannerViewContainer;
    private BannerFragment bannerFragment;
    private static WorkActivity instance;
    public boolean haveTishi; // 是否被提示过，若被提示过，必须

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.d(TAG, "onCreate");

        setContentView(R.layout.activity_work);
        instance = this;

        // 1、几个按钮的初始化，监听
        initClickableView();
        // 2、几个fragment的初始化
        initFragments();

        // 3、初始化BannerViewContrainer，默认显示
        initBannerViewContrainer();

        // 弹出插屏广告
        // 开启后台线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        InterstitialAd.showInterstitialAd(WorkActivity.this);
                    }
                });
            }}).start();
    }
    private void initClickableView(){
        ImageView btnReturn = findViewById(R.id.btn_return);
        aixins = findViewById(R.id.aixins);
        tvZhanshi = findViewById(R.id.tv_zhanshi);
        ImageView imgTishi = findViewById(R.id.img_tishi);

        btnReturn.setOnClickListener(this);
        imgTishi.setOnClickListener(this);
    }
    private void initFragments(){ // 初始化几个Fragment
        wenzhangFragment = new WenzhangFragment();
        victoryFragment = new VictoryFragment();
        defeatFragment = new DefeatFragment();
        bannerFragment = new BannerFragment();

        showFragment(wenzhangFragment, "fragment_wenzhang");
    }
    private void initBannerViewContrainer(){
        // ConstraintLayout constraintLayout = findViewById(R.id.constraint_layout_index);
        // bannerViewContainer = new FrameLayout(this);
        bannerViewContainer = findViewById(R.id.banner_view_container);

        // 设置宽高
        float ratio = 320/60f;
        int width = getResources().getDisplayMetrics().widthPixels;//定一个宽度值，比如屏幕宽度
        int height = (int) (width / ratio);

        ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(
                ConstraintLayout.LayoutParams.MATCH_PARENT,
                height
        );
        // bannerViewContainer.setBackgroundColor(Color.parseColor("#A1FFFFFF"));

        layoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.horizontalBias = 0.5f;
        layoutParams.verticalBias = 0.98f;

        bannerViewContainer.setLayoutParams(layoutParams);
        // constraintLayout.addView(bannerViewContainer);
    }

    @Override
    public void onClick(View v){
        if (v.getId() == R.id.btn_return){
            Log.d(TAG, "点击了返回");

            finish();
        } else if (v.getId() == R.id.img_tishi) {
            Log.d(TAG, "点击了提示");
            // 1、看视频
            //   a、点击提示间隔查询
            //   b、观看激励视频间隔查询
            // 2、调用fragment中的方法，画圈

            // 1、迫使用户玩游戏
            if (haveTishi){
                Toast.makeText(this, "请点击错字", Toast.LENGTH_LONG).show();
                return;
            }
            Context context = this; // 假设在 Activity 中使用
            Runnable controlledFunc = () -> {
                // 2、判断，用户今天是否完成任务
                SharedPreferences prefs = WorkActivity.this.getSharedPreferences("AppPrefs", Context.MODE_PRIVATE);
                int completeTarget = prefs.getInt("completeTarget", 0);

                if (completeTarget == 1){
                    // Log.d("MainApplication", "完成任务，不可调起激励视频: "); // 测试成功
                    Toast.makeText(this, "已完成任务！", Toast.LENGTH_LONG).show();
                    wenzhangFragment.onClickTishi();
                } else {
                    // 展示激励视频
                    RewardVideoAd.showRewardVideoAd(WorkActivity.this);
                }
            };

            IntervalControler.intervalControlForRewardAd(context, controlledFunc, "preTishiTime", 10, "preRewardTime", 50);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();

        Log.d(TAG, "onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();

        Log.d(TAG, "onResume");
        init();
        resumeState();
        setTextOfZhanshi();

        loadBannerAd();
    }

    @Override
    protected void onPause() {
        super.onPause();

        saveState();

        Log.d(TAG, "onPause");
        MainApplication app = (MainApplication)(this.getApplication());
        if (app.getBannerView() != null && app.getBannerView().getParent() != null) {
            ((ViewGroup) app.getBannerView().getParent()).removeView(app.getBannerView());
        }
    }

    @Override
    protected void onStop() {
        super.onStop();

        Log.d(TAG, "onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        Log.d(TAG, "onDestroy");
        instance = null;  // 在销毁时清空引用，减少内存泄漏风险
    }
    public void init(){
        initCurLifeValue();
        initTotalIncorrectChar();
        initCurFindedIncorrectChar();
        setTextOfZhanshi();
    }
    /* 初始化生命值，以及显示爱心的数目 */
    private void initCurLifeValue(){
        /* 当前关卡，剩余生命值 初始化 */
        curLifeValue = 3;

        // 遍历LinearLayout中的所有子视图，设置显示
        for (int i = 0; i < aixins.getChildCount(); i++) {
            View child = aixins.getChildAt(i);
            if (child instanceof ImageView) {
                // 将ImageView添加到数组中
                child.setVisibility(View.VISIBLE);
            }
        }
    }
    public void deleteCurLifeValue(){
        // 当前关卡，剩余生命值 减一
        curLifeValue -= 1;
        // UI变换（爱心隐藏一个）
        for (int i = 0; i < aixins.getChildCount(); i++) {
            View child = aixins.getChildAt(i);
            if (child instanceof ImageView) {
                int visibility = child.getVisibility();

                if (visibility != View.INVISIBLE){
                    child.setVisibility(View.INVISIBLE);
                    break;
                }
            }
        }
        Log.d("GridLayout", "选错了，生命值减一");
        if (curLifeValue == 0){
            // UI变换（弹出闯关失败）
            showFragment(defeatFragment, "fragment_defeat");
            Log.d(TAG, "deleteCurLifeValue: 闯关失败！");
            // 弹出插屏广告
            // 开启后台线程
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            InterstitialAd.showInterstitialAd(WorkActivity.this);
                        }
                    });
                }}).start();
            // haveTishi
            haveTishi = false;
        }
    }
    /* 当前关卡，所有错字总数 初始化，基于wenzhang_fragment的getTotalIncorrectChar方法 */
    private void initTotalIncorrectChar(){

        // totalIncorrectChar = 10;
        totalIncorrectChar = wenzhangFragment.getTotalIncorrectChar();
    }
    /* 当前关卡，已经找出来的错字数 初始化 */
    private void initCurFindedIncorrectChar(){
        curFindedIncorrectChar = 0;
    }
    public void addCurFindedIncorrectChar(){
        /* 当前关卡，已经找出来的错字数 加一 */
        curFindedIncorrectChar += 1;
        setTextOfZhanshi();
        if (curFindedIncorrectChar == totalIncorrectChar){
            // 弹出闯关成功，以及更新缓存
            showFragment(victoryFragment, "fragment_victory");

            SharedPreferences prefs = this.getSharedPreferences("AppPrefs", Context.MODE_PRIVATE);
            int task1Cur = prefs.getInt("task1Cur", 0);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putInt("task1Cur", task1Cur+1);
            editor.apply();
            // 弹出插屏广告
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            InterstitialAd.showInterstitialAd(WorkActivity.this);
                        }
                    });
                }}).start();
            haveTishi = false;
        }
    }
    public void deleteCurFindedIncorrectChar(){
        /* 当前关卡，已经找出来的错字数 减一 */
        curFindedIncorrectChar -= 1;
        setTextOfZhanshi();
    }
    private void setTextOfZhanshi(){
        String tishi = "找出错误的字，已完成：（" + curFindedIncorrectChar + "/" + totalIncorrectChar + "）";
        // Log.d(TAG, "setTextOfTishi: tishi");
        tvZhanshi.setText(tishi);
        tvZhanshi.setTextSize(16);
    }
    private void loadBannerAd(){
        MainApplication app = (MainApplication)getApplication();

        // 1、定义子视图（View）在 FrameLayout 中的布局特性（也就是，定义bannerView在FrameLayout 中的布局特性）
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.CENTER;
        if (app.getBannerView() != null && app.getBannerView().getParent() == null) {
            bannerViewContainer.addView(app.getBannerView(), layoutParams);
        }
        if (app.getBannerView() != null){
            app.getBannerView().loadAd();
        }
    }
    private void showFragment(Fragment fragment, String str) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        if (fragment.isAdded()) {
            fragmentTransaction.show(fragment);
        } else {
            if (str.equals("fragment_wenzhang")){
                fragmentTransaction.add(R.id.fragment_container, fragment, str);
            } else if (str == "fragment_banner") {
                fragmentTransaction.add(R.id.banner_view_container, fragment, str);
            } else {
                fragmentTransaction.add(R.id.fragment_container_full, fragment, str);
            }

        }
        fragmentTransaction.commit();
    }
    /* 以概率展示插屏广告 */
    public void showInterstitialAdByProbability(){
        double probability = 0.08;

        Random random = new Random();
        double randomValue = random.nextDouble(); // 生成一个 [0, 1) 范围内的随机数

        if (randomValue < probability) {
            // System.out.println("这句话被打印出来了！");
            // 弹出插屏广告
            // 开启后台线程
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            InterstitialAd.showInterstitialAd(WorkActivity.this);
                        }
                    });
                }}).start();
        }
    }
    public static WorkActivity getInstance() {
        return instance;
    }
    /* 保存当前生命值、当前以及找出来的错字数目 */
    /* on pause时调用 */
    private void saveState(){
        savedLifeValue = curLifeValue;
        savedFindedIncorrectChar = curFindedIncorrectChar;
    }
    /* 恢复当前生命值、当前以及找出来的错字数目 */
    /* on resume时调用 */
    private void resumeState(){
        curLifeValue = savedLifeValue;
        curFindedIncorrectChar = savedFindedIncorrectChar;
    }
}